<template>
  <div class="overflow-hidden">
    <div class="form-title">企业基本信息</div>
    <div class="form-container">
      <el-form ref="enterpriseForm" :model="enterpriseForm" label-width="10rem" :rules="formRules">
        <div class="form-sub-title">基本信息</div>
        <div class="w-full flex sm:justify-center  md:justify-between content-center flex-wrap sm:reponsive-form">
          <el-form-item label="企业名称:" class="fixed-input-w" prop="companyName"><el-input v-model="enterpriseForm.companyName"></el-input></el-form-item>
          <el-form-item label="统一社会信用代码:" class="fixed-input-w" prop="creditCode"><el-input v-model="enterpriseForm.creditCode"></el-input></el-form-item>
          <el-form-item label="注册地址:" class="fixed-input-w" prop="area">
            <el-cascader
              v-model="area"
              :options="areaOptions"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childern'
              }"
              placeholder="请选择"
              clearable
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="企业性质:" class="fixed-input-w" prop="nature">
            <el-select v-model="enterpriseForm.nature" filterable placeholder="请选择">
              <el-option v-for="item in natureOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="办公地址:" class="fixed-input-w" prop="address"><el-input v-model="enterpriseForm.address"></el-input></el-form-item>
          <el-form-item label="注册资金( 万元 ):" class="fixed-input-w" prop="registeredMoney">
            <el-input type="age" v-model.number="enterpriseForm.registeredMoney"></el-input>
          </el-form-item>
          <el-form-item label="实际资金:" class="fixed-input-w" prop="trueMoney"><el-input type="age" v-model.number="enterpriseForm.trueMoney"></el-input></el-form-item>
        </div>

        <div class="form-sub-title">法人信息</div>
        <div class="w-full flex sm:justify-center  md:justify-between content-center flex-wrap sm:reponsive-form">
          <el-form-item label="法人姓名:" class="fixed-input-w" prop="legalPerson"><el-input v-model="enterpriseForm.legalPerson"></el-input></el-form-item>
          <el-form-item label="法人身份证号:" class="fixed-input-w" prop="legalPersonCode"><el-input v-model="enterpriseForm.legalPersonCode"></el-input></el-form-item>
          <el-form-item label="国籍:" class="fixed-input-w" prop="nationality">
            <el-select v-model="enterpriseForm.nationality" placeholder="无" style="width: 100%" clearable filterable size="small">
              <el-option v-for="(item, index) in nationOptions" :key="item.name + index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="手机号:" class="fixed-input-w" prop="legalPhone"><el-input v-model="enterpriseForm.legalPhone"></el-input></el-form-item>
          <el-form-item label="联系电话:" class="fixed-input-w" prop="legalFixedPhone"><el-input v-model="enterpriseForm.legalFixedPhone"></el-input></el-form-item>
          <el-form-item label="邮政编码:" class="fixed-input-w" prop="legalPostCode"><el-input v-model="enterpriseForm.legalPostCode"></el-input></el-form-item>
          <el-form-item label="电子邮箱:" class="fixed-input-w" prop="email"><el-input v-model="enterpriseForm.email"></el-input></el-form-item>
        </div>

        <el-form-item><el-button type="primary" style="margin-top: 1rem; width: 88%;" @click="onSubmit">保存</el-button></el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import SelectAddress from '@/components/SelectAddress';
import { getCompanyInfo, updateCompanyInfo } from '@/api/manageInformation/baseInfo';
import { getSpecificArea } from '@/api/system/user';
import { queryNationList } from '@/api/';

export default {
  name: 'BaseInfo',
  components: {
    SelectAddress
  },
  data() {
    // 表单校验数字使用
    var checkFormNumberV = (rule, value, callback) => {
      this.$emit('checkFormNumberV', rule, value, callback);
    };

    // 校验手机号
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback();
      }
      let reg = /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error('请输入有效手机号'));
        } else {
          callback();
        }
      }, 1000);
    };

    // 校验三级联动下拉选
    var validateArea = (rule, value, callback) => {
      if (!value) {
        return callback();
      }

      this.$nextTick(() => {
        if (!this.area.length) {
          return callback(new Error('注册地址不能为空'));
        } else {
          return callback();
        }
      });
    };

    return {
      // 当前用户的公司id
      companyManagerId: undefined,

      // 当前是否可以进行修改
      isEdit: true,
      status: true,

      // 所属区域存储
      area: [],
      // 省市区三级联动选项
      areaOptions: [],

      // 表单
      enterpriseForm: {
        companyName: '',
        creditCode: '',
        registeredAddress: '',
        area: [],

        nature: '',
        address: '',
        registeredMoney: '',
        trueMoney: '',

        legalPerson: '',
        legalPersonCode: '',
        nationality: 7,
        legalPhone: '',
        legalFixedPhone: '',
        legalPostCode: '',
        email: '',

        introduction: ''
      },

      // 企业规模
      scaleOptions: [],
      // 企业性质
      natureOptions: [],
      // 国籍列表
      nationOptions: [],

      // 验证规则
      formRules: {
        companyName: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
        creditCode: [
          {
            required: true,
            message: '请输入社会统一信用代码',
            trigger: 'blur'
          }
        ],
        area: [{ required: true, validator: validateArea }],
        registeredMoney: [{ type: 'number', trigger: 'blur' }],
        trueMoney: [{ type: 'number', trigger: 'blur' }],
        legalPhone: [{ validator: checkPhone, trigger: 'blur' }]
      },

      // 字典名
      dictNameList: ['declare_enterprise_natrue', 'declare_enterprise_scale']
    };
  },
  created() {
    this.initDictList();
    // 获取国籍列表
    queryNationList().then(res => {
      this.nationOptions = res.data;
    });
  },
  mounted() {
    // 获取用户id
    this.companyManagerId = this.$store.state.user.companyId;

    // 获取到省市区信息以后 再开始赋值
    this.getSpecificAreaFun().then(() => {
      // 如果存在用户id则进行用户信息获取s
      if (this.companyManagerId) {
        this.isEdit = true;
        getCompanyInfo(this.companyManagerId).then(res => {
          this.enterpriseForm = res.data;
          if (this.enterpriseForm.nationality == null || this.enterpriseForm.nationality == undefined || this.enterpriseForm.nationality == '') {
            this.enterpriseForm.nationality = 7;
          }
          this.enterpriseForm.nationality = Number(this.enterpriseForm.nationality);

          if (this.enterpriseForm.area) {
            // 将返回的数组重新转换为number类型 防止数据无法还原
            this.area = this.enterpriseForm.area.split(',').map(Number);
          }
        });
      } else {
        this.isEdit = false;
      }
    });
  },
  methods: {
    // 初始化所有字典类别
    initDictList() {
      this.getDicts(this.dictNameList[0]).then(res => {
        if (res.code == 200) {
          this.natureOptions = res.data;
        }
      });
      this.getDicts(this.dictNameList[1]).then(res => {
        if (res.code == 200) {
          this.scaleOptions = res.data;
        }
      });
    },

    /* 查询省市区信息 */
    getSpecificAreaFun() {
      return new Promise((resolve, reject) => {
        getSpecificArea().then(res => {
          this.areaOptions = [res.data];
          resolve();
        });
      });
    },
    // 省市区三级联动
    getRegiAddress(finalAddress) {
      let addressStr = JSON.stringify(finalAddress);
      this.enterpriseForm.area = addressStr;
    },

    /* 根据省市区三级联动变化获取数据 */
    handleChange(value) {},
    /* END */

    // 提交
    onSubmit() {
      this.$refs['enterpriseForm'].validate(valid => {
        if (valid) {
          let obj = JSON.parse(JSON.stringify(this.enterpriseForm));
          obj.area = this.area ? this.area.join(',') : this.area;
          updateCompanyInfo(JSON.stringify(obj)).then(response => {
            this.isEdit = true;
            this.status = true;
            getCompanyInfo(this.companyManagerId).then(res => {
              this.enterpriseForm = res.data;
              this.area = this.enterpriseForm.area.split(',');
              if (this.enterpriseForm.nationality == null || this.enterpriseForm.nationality == undefined || this.enterpriseForm.nationality == '') {
                this.enterpriseForm.nationality = 7;
              }
              this.enterpriseForm.nationality = Number(this.enterpriseForm.nationality);
              this.msgSuccess('修改成功');
            });
          });
        } else {
          this.msgError('有必填项还未填写，请重试！');
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.tag {
  @apply py-2 cursor-pointer  px-4 mr-4 mb-2 rounded-md border;
  &:hover {
    @apply bg-blue-400 text-white;
  }
}

.fixed-input-w {
  ::v-deep input {
    @apply w-96;
  }
}

.form-title {
  @apply text-center text-xl border-b p-3 mt-4;
}

.form-sub-title {
  @apply p-2 mt-4 mb-8  text-xl ml-16  border-b border-dashed border-gray-400;
  &:first-child {
    @apply mt-0;
  }
}

/** 修改表单内无法修改时的样式 */
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #fff;
  border-color: #dfe4ed;
  color: #333;
  /* border: 0; */
}

/* 当前如果是无法点击的状态修改表单的样式 */
.form-disabled {
  ::v-deep .el-input__inner {
    border: 0;
  }

  ::v-deep input::-webkit-input-placeholder,
  ::v-deep textarea::-webkit-input-placeholder,
  ::v-deep .el-cascader__search-input {
    color: #666;
  }
  ::v-deep input::-moz-input-placeholder,
  ::v-deep textarea::-moz-input-placeholder {
    color: #666;
  }
  ::v-deep input::-ms-input-placeholder,
  ::v-deep textarea::-ms-input-placeholder {
    color: #666;
  }

  ::v-deep .el-input__suffix {
    display: none;
  }

  ::v-deep .el-textarea__inner {
    margin-top: 0.2rem;
    border: 0;
    resize: none;
  }

  ::v-deep .el-upload {
    display: none;
  }

  .el-upload__tip {
    margin-left: 0.7rem;
    margin-top: 0.785rem;
  }
}
</style>
